package control;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import pojo.News_users;
import utils.PreHandle;

public class DoLogin extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public DoLogin() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("utf-8");
		String uname = request.getParameter("uname");
		String upwd = request.getParameter("upwd");
		String sql = "select * from news_users where uname=? and upwd=?";
		List<News_users> list = PreHandle.query(sql, News_users.class, uname, upwd);
		News_users news_users = list.size() == 0 ? null : list.get(0);
		if (news_users != null) {
			if ("1".equals(request.getParameter("keep"))) {
				Cookie cookieName = new Cookie("uname", "" + uname);
				cookieName.setMaxAge(86400);
				cookieName.setPath(request.getContextPath() + "/");
				Cookie cookiePass = new Cookie("upwd", "" + upwd);
				cookiePass.setMaxAge(86400);
				cookiePass.setPath(request.getContextPath() + "/");
				response.addCookie(cookieName);
				response.addCookie(cookiePass);

			}
			request.getSession().setAttribute("USER_LOGIN", news_users);
			request.getRequestDispatcher("doShowAdmin").forward(request, response);
			return;
		} else {
			response.sendRedirect("doInitialHomePage");
			return;
		}
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
